package net.hyperz.water.levels;

import java.util.List;

import org.jsoup.nodes.Document;

import net.hyperz.water.levels.utils.StationContent;
import net.hyperz.water.levels.utils.StationContent.Station;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class StationListFragment extends ListFragment {

    private static final String STATE_ACTIVATED_POSITION = "activated_position";
    
    private Callbacks mCallbacks = sDummyCallbacks;
    private int mActivatedPosition = ListView.INVALID_POSITION;
    private StationContent sc = new StationContent();
    
    public interface Callbacks {

        public void onItemSelected(String id, String name);
    }

    private static Callbacks sDummyCallbacks = new Callbacks() {
        public void onItemSelected(String id, String name) {
        }
    };
    
    public StationListFragment() {
    }
    
    @Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		new LoadStationList().execute("BC");
	}
    
    private class LoadStationList extends AsyncTask<String, Void, List<Station>> {
		ProgressDialog progress = new ProgressDialog(getActivity());
		
		@Override
        public void onPreExecute() {
			progress.setCanceledOnTouchOutside(false);
			progress.setCancelable(false);
			progress.setMessage("Loading Station List ...");
			progress.show();
		}
		
		@Override
        public void onPostExecute(List<Station> stations) {
			setListAdapter(new ArrayAdapter<StationContent.Station>(getActivity(),
	                android.R.layout.simple_list_item_activated_2,
	                android.R.id.text1,
	                stations));
			
			progress.dismiss();
		}
		
		@Override
		protected List<Station> doInBackground(String... params) {
			Document doc = new Document("http://www.wateroffice.ec.gc.ca");
			doc.html(StationContent.convertStreamToString(getActivity().getResources().openRawResource(R.raw.bc)));
			return sc.getStations(doc);
			//return sc.getStations(null);
		}
	}
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (savedInstanceState != null && savedInstanceState
                .containsKey(STATE_ACTIVATED_POSITION)) {
            setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof Callbacks)) {
            throw new IllegalStateException("Activity must implement fragment's callbacks.");
        }

        mCallbacks = (Callbacks) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = sDummyCallbacks;
    }

    @Override
    public void onListItemClick(ListView listView, View view, int position, long id) {
        super.onListItemClick(listView, view, position, id);
        mCallbacks.onItemSelected(sc.STATIONS.get(position).id, sc.STATIONS.get(position).name);
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mActivatedPosition != ListView.INVALID_POSITION) {
            outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
        }
    }

    public void setActivateOnItemClick(boolean activateOnItemClick) {
        getListView().setChoiceMode(activateOnItemClick
                ? ListView.CHOICE_MODE_SINGLE
                : ListView.CHOICE_MODE_NONE);
    }

    public void setActivatedPosition(int position) {
        if (position == ListView.INVALID_POSITION) {
            getListView().setItemChecked(mActivatedPosition, false);
        } else {
            getListView().setItemChecked(position, true);
        }
        
        mActivatedPosition = position;
    }
}
